﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcDeviceManager.Controllers;

namespace DeviceManager.Filter
{
    public class SessionFilter : FilterAttribute, IAuthorizationFilter
    {
        IList<string> iSession=new List<string>();
        private string context = "";
       // private string context = "/DeviceManager";
        public SessionFilter()
        {


            iSession.Add(context + "/File/AjaxUploadFile");
            iSession.Add(context + "/Login/LogOn");
            iSession.Add(context + "/");
            iSession.Add(context + "/Login/LogOut");
        }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            string path = filterContext.HttpContext.Request.CurrentExecutionFilePath;
            System.Diagnostics.Trace.WriteLine(path);
            if (iSession.Contains(path))
            {
                return;
            }
            else
            {
                bool isNew = filterContext.HttpContext.Session.IsNewSession;
                bool isTimeOut = (filterContext.HttpContext.Session[Constant.LOGIN_USER] == null);
                if (isNew || isTimeOut)
                {
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        object data = new { error = "对不起，对不起系统超时，请重新登陆后再试！" };
                        JsonResult result = new JsonResult();
                        result.Data = data;
                        filterContext.Result = result;
                    }
                    else
                    {
                        filterContext.Result = new RedirectResult("~/Login/LogOn?error=对不起，对不起系统超时，请重新登陆后再试！");
                    }
                    return;
                }
            }
        }
    }
}